﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Polyline = Esri.ArcGISRuntime.Geometry.Polyline;

namespace classTest
{
    /// <summary>
    /// LocationQueryWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LocationQueryWindow : Window
    {
        private MapView MyMapView;
        private Dictionary<Feature, FeatureLayer> selectLayer = null;
        private MapPoint fromPoint;
        private MapPoint toPoint;
        private string networkPath;
        private string networkName;
        private MainWindow mainWindow;
        private GraphicsOverlay _routeGraphicsOverlay = new GraphicsOverlay();


        public LocationQueryWindow(MapView mapView, MainWindow mainWindow1)
        {
            InitializeComponent();
            MyMapView = mapView;
            mainWindow = mainWindow1;

            var picPath = $"..\\..\\Image\\scauImage\\1.jpg";
            imageFeature.Source = new BitmapImage(new Uri(picPath, UriKind.Relative));
            MyMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (searchContent.Text == null)
            {
                MessageBox.Show("搜索关键字不能为空");
                return;
            }
            if (searchResult.Items.Count > 0) searchResult.Items.Clear();

            LocationQuery();
        }

        // 查询
        private async void LocationQuery()
        {
            LayerCollection layers = MyMapView.Map.OperationalLayers;
            QueryParameters qParams = new QueryParameters();//创建查询参数对象
            qParams.WhereClause = $"name like '%{searchContent.Text}%'";// 查询时会自动忽略大小写
            progressBar.Value = 0;
            progressBar.Visibility = Visibility.Visible;
            int count = layers.Count;
            int searchCount = 0;
            for (int i = count - 1; i >= 0; i--)
            {
                FeatureLayer featureLayer = layers[i] as FeatureLayer;
                FeatureQueryResult result = null;
                try
                {
                    result = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams); //在表上进行查询
                }
                catch
                {
                    //Console.WriteLine("error");
                }

                if (result != null && result.Count() > 0)
                {
                    List<string> fields = result.First().Attributes.Keys.ToList();
                    int index = 0;
                    for (int j = 0; j < fields.Count(); j++)
                    {
                        if (fields[j].ToLower() == "name")
                        {
                            index = j;
                        }
                    }
                    foreach (Feature f in result)
                    {
                        searchCount++;
                        Dictionary<Feature, FeatureLayer> collectLayer = new Dictionary<Feature, FeatureLayer>();
                        collectLayer.Add(f, featureLayer);
                        ListBoxItem lbi = new ListBoxItem();
                        lbi.Content = f.Attributes.Values.ElementAt(index).ToString().Trim();
                        lbi.DataContext = collectLayer;
                        searchResult.Items.Add(lbi);
                    }
                }
                progressBar.Value = 100 * (count - i + 1) / count;
            }
            searchResultTip.Content = $"共搜索到{searchCount}个图层要素";
            progressBar.Visibility = Visibility.Hidden;
        }

        //开始搜索
        private async void SearchResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (searchResult.SelectedIndex == -1) return;
            if (selectLayer != null) selectLayer.Values.First().ClearSelection();
            selectLayer = (searchResult.SelectedItem as ListBoxItem).DataContext as Dictionary<Feature, FeatureLayer>;
            Feature feature = selectLayer.Keys.First();
            FeatureLayer featureLayer = selectLayer.Values.First();
            try
            {
                featureLayer.SelectFeature(feature);
            }
            catch
            {

            }
            

            Random random = new Random();
            var picPath = $"..\\..\\Image\\scauImage\\{random.Next(1, 39)}.jpg";
            imageFeature.Source = new BitmapImage(new Uri(picPath, UriKind.Relative));
            dataGrid.ItemsSource = feature.Attributes;
            currentLayerTip.Content = $"当前要素来自图层：{featureLayer.Name}";

            if(feature.Geometry.GeometryType == GeometryType.Point)
            {
                await MyMapView.SetViewpointCenterAsync(feature.Geometry as MapPoint,1520);
            }
            else
            {
                await MyMapView.SetViewpointGeometryAsync(feature.Geometry.Extent);
            }
            


            // 路线的
            List<string> fields = feature.Attributes.Keys.ToList();
            int index = 0;
            for (int j = 0; j < fields.Count(); j++)
            {
                if (fields[j].ToLower() == "name")
                {
                    index = j;
                }
            }
            toTextBox.Text = feature.Attributes.Values.ElementAt(index).ToString().Trim();
            toPoint = new MapPoint((feature.Geometry.Extent.XMax + feature.Geometry.Extent.XMin) / 2, (feature.Geometry.Extent.YMin + feature.Geometry.Extent.YMax) / 2, feature.Geometry.SpatialReference);
            toPoint = GeometryEngine.Project(toPoint, new SpatialReference(3857)) as MapPoint;
            goThere.IsEnabled = true;
        }


        private void Window_Closed(object sender, EventArgs e)
        {
            if (selectLayer != null) selectLayer.Values.First().ClearSelection();
            if (_routeGraphicsOverlay != null) MyMapView.GraphicsOverlays.Remove(_routeGraphicsOverlay);
        }


        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (fromPoint == null)
            {
                MessageBox.Show("请先点击在地图点一个点，再点击出发点的输入框自动输入");
                return;
            }
            if (mainWindow.networkPath == null)
            {
                MessageBox.Show("请先加载网络图层");
                return;
            }
            if (_routeGraphicsOverlay.Graphics.Count > 0) _routeGraphicsOverlay.Graphics.Clear();
            networkPath = mainWindow.networkPath;
            networkName = mainWindow.networkName;
            var picPath1 = @"..\..\Image\Icon\car.png";
            PictureMarkerSymbol startSymbol;
            using (System.IO.FileStream picStream = new System.IO.FileStream(picPath1,
            System.IO.FileMode.Open))
            {
                // pass the image file stream to the symbol constructor
                startSymbol = await PictureMarkerSymbol.CreateAsync(picStream);
            }
            startSymbol.Width = 30;
            startSymbol.Height = 30;
            startSymbol.OffsetY = startSymbol.Height / 2;
            Graphic fromGraphic = new Graphic(fromPoint, startSymbol);
            _routeGraphicsOverlay.Graphics.Add(fromGraphic);

            var picPath2 = @"..\..\Image\Icon\to.png";
            PictureMarkerSymbol toSymbol;
            using (System.IO.FileStream picStream = new System.IO.FileStream(picPath2,
            System.IO.FileMode.Open))
            {
                // pass the image file stream to the symbol constructor
                toSymbol = await PictureMarkerSymbol.CreateAsync(picStream);
            }
            toSymbol.Width = 30;
            toSymbol.Height = 30;
            toSymbol.OffsetY = toSymbol.Height / 2;
            Graphic toGraphic = new Graphic(toPoint, toSymbol);
            _routeGraphicsOverlay.Graphics.Add(toGraphic);


            List<Stop> routeStops = new List<Stop>();
            try
            {
                RouteTask solveRouteTask = await RouteTask.CreateAsync(networkPath, networkName);
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();
                routeParams.ReturnStops = true;
                routeParams.ReturnDirections = true;
                if (fromPoint == null && toPoint == null) return;
                Stop stop1 = new Stop(fromPoint);
                Stop stop2 = new Stop(toPoint);
                routeStops.Add(stop1);
                routeStops.Add(stop2);
                routeParams.SetStops(routeStops);
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);
                Route route = solveRouteResult.Routes.First();
                Polyline routePolyline = route.RouteGeometry;
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 3.0);
                Graphic routeGraphic = new Graphic(routePolyline, routeSymbol);
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);

        }
            catch
            {
                MessageBox.Show("出现错误");
            }
}

        private void FromTextBox_GotMouseCapture(object sender, MouseEventArgs e)
        {
            if (mainWindow.location == null) return;
            fromPoint = new MapPoint(mainWindow.location.X, mainWindow.location.Y, new SpatialReference(3857));
            fromTextBox.Text = $"{Math.Round(fromPoint.X, 3)} {Math.Round(fromPoint.Y, 3)}";
        }

        private void GoThere_Click(object sender, RoutedEventArgs e)
        {
            if (routeBox.IsVisible)
            {
                goThere.Content = "go there";
                routeBox.Visibility = Visibility.Hidden;
            }
            else{
                goThere.Content = "return";
                routeBox.Visibility = Visibility.Visible;
            }
            
        }

        private void SearchContent_GotFocus(object sender, RoutedEventArgs e)
        {
            searchContent.Text = "";
        }
    }
}
